package com.macro.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.macro.mall.dto.UmsMenuNode;
import com.macro.mall.service.UmsMenuService;
import com.macro.mapper.UmsMenuMapper;
import com.macro.model.UmsMenu;
import com.macro.model.UmsMenuExample;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UmsMenuServiceImpl implements UmsMenuService {
    @Autowired
    private UmsMenuMapper menuMapper;

    @Override
    public int create(UmsMenu umsMenu) {
        umsMenu.setCreateTime(new Date());
        return menuMapper.insert(umsMenu);
    }

    @Override
    public int update(Long id, UmsMenu umsMenu) {
        umsMenu.setId(id);
        return menuMapper.updateByPrimaryKeySelective(umsMenu);
    }

    @Override
    public UmsMenu getItem(Long id) {
        return menuMapper.selectByPrimaryKey(id);
    }

    @Override
    public int delete(Long id) {
        return menuMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<UmsMenu> list(Long parentId, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        UmsMenuExample example = new UmsMenuExample();
        example.setOrderByClause("sort desc");
        example.createCriteria().andParentIdEqualTo(parentId);
        return menuMapper.selectByExample(example);
    }

    @Override
    public List<UmsMenuNode> treeList() {
        List<UmsMenu> menus = menuMapper.selectByExample(new UmsMenuExample());
        List<UmsMenuNode> nodes = menus.stream().filter(menu -> menu.getParentId().equals(0L))
                .map(menu -> convertMenuNode(menu, menus))
                .collect(Collectors.toList());

        return nodes;
    }

    // 转化为树形菜单  递归
    private UmsMenuNode convertMenuNode(UmsMenu menu, List<UmsMenu> menus) {
        UmsMenuNode node = new UmsMenuNode();
        BeanUtils.copyProperties(menu,node);
        List<UmsMenuNode> children = menus.stream()
                .filter(subMenu -> subMenu.getParentId().equals(menu.getId()))
                .map(subMenu -> convertMenuNode(subMenu,menus)).collect(Collectors.toList());

        node.setChildren(children);
        return node;
    }

    @Override
    public int updateHidden(Long id, Integer hidden) {
       UmsMenu menu = new UmsMenu();
       menu.setHidden(hidden);
       menu.setId(id);
       return menuMapper.updateByPrimaryKeySelective(menu);
    }
}
